@echo off
chcp 65001 >nul
echo.
echo ================================
echo    洗护帮用户端 - 快速启动
echo ================================
echo.

:: 设置颜色
set "GREEN=[92m"
set "YELLOW=[93m"
set "RED=[91m"
set "BLUE=[94m"
set "NC=[0m"

:: 检查Java环境
echo %BLUE%[1/6] 检查Java环境...%NC%
java -version >nul 2>&1
if %errorlevel% neq 0 (
    echo %RED%❌ Java未安装或未配置环境变量%NC%
    echo 请安装JDK 11或17并配置JAVA_HOME
    pause
    exit /b 1
) else (
    echo %GREEN%✅ Java环境正常%NC%
)

:: 检查Android SDK
echo %BLUE%[2/6] 检查Android SDK...%NC%
if not defined ANDROID_HOME (
    echo %RED%❌ ANDROID_HOME环境变量未设置%NC%
    echo 请设置ANDROID_HOME指向Android SDK目录
    pause
    exit /b 1
) else (
    echo %GREEN%✅ Android SDK路径: %ANDROID_HOME%%NC%
)

:: 检查ADB
echo %BLUE%[3/6] 检查ADB工具...%NC%
adb version >nul 2>&1
if %errorlevel% neq 0 (
    echo %RED%❌ ADB工具未找到%NC%
    echo 请确保Android SDK platform-tools在PATH中
    pause
    exit /b 1
) else (
    echo %GREEN%✅ ADB工具正常%NC%
)

:: 检查设备连接
echo %BLUE%[4/6] 检查设备连接...%NC%
for /f "skip=1" %%i in ('adb devices 2^>nul') do (
    set "device_found=true"
    goto :device_check_done
)
:device_check_done
if not defined device_found (
    echo %YELLOW%⚠️  没有检测到连接的设备%NC%
    echo 请连接Android设备或启动模拟器
    echo.
    echo 是否要启动Android模拟器？ (y/n)
    set /p start_emulator=
    if /i "%start_emulator%"=="y" (
        echo 启动模拟器...
        start "" emulator -avd Pixel_4_API_30
        echo 等待模拟器启动...
        timeout /t 10 /nobreak >nul
    )
) else (
    echo %GREEN%✅ 设备连接正常%NC%
    adb devices
)

:: 构建应用
echo %BLUE%[5/6] 构建应用...%NC%
echo 正在构建Debug版本...
call gradlew.bat assembleDebug
if %errorlevel% neq 0 (
    echo %RED%❌ 应用构建失败%NC%
    pause
    exit /b 1
) else (
    echo %GREEN%✅ 应用构建成功%NC%
)

:: 安装并启动应用
echo %BLUE%[6/6] 安装并启动应用...%NC%
echo 正在安装应用...
call gradlew.bat installDebug
if %errorlevel% neq 0 (
    echo %RED%❌ 应用安装失败%NC%
    pause
    exit /b 1
) else (
    echo %GREEN%✅ 应用安装成功%NC%
)

echo 正在启动应用...
adb shell am start -n com.laundry.user/.ui.main.MainActivity
if %errorlevel% neq 0 (
    echo %RED%❌ 应用启动失败%NC%
    pause
    exit /b 1
) else (
    echo %GREEN%✅ 应用启动成功%NC%
)

echo.
echo ================================
echo    🎉 用户端应用启动完成！
echo ================================
echo.
echo 📱 应用已在设备上运行
echo 📊 查看日志: gradlew.bat logcat
echo 🔧 重新构建: gradlew.bat assembleDebug
echo 📦 重新安装: gradlew.bat installDebug
echo.

:: 询问是否查看日志
echo 是否要查看应用日志？ (y/n)
set /p view_logs=
if /i "%view_logs%"=="y" (
    echo.
    echo 正在显示应用日志... (按Ctrl+C停止)
    adb logcat -v time com.laundry.user:V *:S
)

pause
